package com.hkbigdata.mall.miaosha.service.impl;

import com.hkbigdata.mall.common.api.CommonResult;
import com.hkbigdata.mall.miaosha.component.CancelOrderSender;
import com.hkbigdata.mall.miaosha.dto.OrdOrderDTO;
import com.hkbigdata.mall.miaosha.mapper.OrdOrderMapper;
import com.hkbigdata.mall.miaosha.module.OrdOrder;
import com.hkbigdata.mall.miaosha.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 前台订单管理Service
 * Created by macro on 2018/8/30.
 */
@Service
public class OrderServiceImpl implements OrderService {
    private static Logger LOGGER = LoggerFactory.getLogger(OrderServiceImpl.class);
    @Autowired
    private CancelOrderSender cancelOrderSender;
    @Autowired
    private OrdOrderMapper orderMapper;

    @Override
    public CommonResult generateOrder(OrdOrderDTO orderParam) {
        //todo 执行一系类下单操作，具体参考mall项目
        LOGGER.info("process generateOrder");

        OrdOrder order = new OrdOrder();
        BeanUtils.copyProperties(orderParam, order);
        // insert需要满足返回 主键id
        order.setOrderSn(String.valueOf(System.currentTimeMillis()));
        orderMapper.insert(order);

        //下单完成后开启一个延迟消息，用于当用户没有付款时取消订单（orderId应该在下单后生成）
        sendDelayMessageCancelOrder(order.getId());

        return CommonResult.success(null, "下单成功");
    }

    @Override
    public void cancelOrder(Long orderId) {
        //todo 执行一系类取消订单操作，具体参考mall项目
        OrdOrder order = new OrdOrder();
        order.setStatus(5);
        order.setId(orderId);
        orderMapper.updateByPrimaryKeySelective(order);
        LOGGER.info("process cancelOrder orderId:{},订单状态已经修改为5",orderId);
        // 因为商品模块待定，订单的相关商品库存释放有待开发
    }

    private void sendDelayMessageCancelOrder(Long orderId) {
        //获取订单超时时间，假设为60分钟
        long delayTimes = 3 * 1000; //ms为单位
        //发送延迟消息
        cancelOrderSender.sendMessage(orderId, delayTimes);
    }

}
